<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="70%"
    :before-close="handleClose"
  >
    <div class="manage-dialog">
      <el-form
        inline
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="130px"
      >
        <el-form-item label="商品名称" prop="goods_name">
          <el-input
            placeholder="输入商品名称"
            style="width: 100%"
            v-model="ruleForm.goods_name"
          />
        </el-form-item>
        <el-form-item label="商品标签" prop="marks">
          <el-select
            v-model="ruleForm.marks"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="商品标签"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in labelOptions"
              :key="item.id"
              :label="item.mark_name"
              :value="item.mark_name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" prop="cateid">
          <el-tree-select
            default-expand-all
            node-key="id"
            filterable
            v-model="ruleForm.cateid"
            :data="classOptions"
            check-strictly
            clearable
            :render-after-expand="false"
            :props="{
              label: 'name',
              children: 'sub',
            }"
            style="width: 100% !important"
            placeholder="分类编号"
          >
          </el-tree-select>
        </el-form-item>
        <el-form-item label="是否积分专区" prop="is_integral">
          <el-radio-group v-model="ruleForm.is_integral">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品类型" prop="goods_kind">
          <el-select
            v-model="ruleForm.goods_kind"
            placeholder="商品类型"
            style="width: 100%"
            clearable
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="商品封面"
          style="width: 100%"
          v-loading="coverLoading"
        >
          <div class="img-box" v-for="(item, i) in coverImgList" :key="i">
            <img :src="item.url" alt="" />

            <div class="occlusion">
              <el-icon class="del" @click="coverRemove(i)">
                <IEpDelete />
              </el-icon>
            </div>
          </div>
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :show-file-list="false"
            :file-list="coverImgList"
            :on-change="coverOnChange"
          >
            <el-icon>
              <IEpPlus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="轮播图片"
          style="width: 100%"
          v-loading="sliderLoading"
        >
          <div class="img-box" v-for="(item, i) in sliderImgList" :key="i">
            <img :src="item.url" alt="" />

            <div class="occlusion">
              <el-icon class="del" @click="sliderRemove(i)">
                <IEpDelete />
              </el-icon>
            </div>
          </div>
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :show-file-list="false"
            :file-list="sliderImgList"
            :on-change="sliderOnChange"
          >
            <el-icon>
              <IEpPlus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="广告图片"
          style="width: 100%"
          v-loading="picsLoading"
        >
          <div class="img-box" v-for="(item, i) in picsImgList" :key="i">
            <img :src="item.url" alt="" />
            <div class="occlusion">
              <el-icon class="del" @click="picsRemove(i)">
                <IEpDelete />
              </el-icon>
            </div>
          </div>
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :show-file-list="false"
            :file-list="picsImgList"
            :on-change="picsOnChange"
          >
            <el-icon>
              <IEpPlus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频" style="width: 100%">
          <el-upload
            class="upload-demo"
            action="#"
            :limit="1"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="videoOnChange"
            :on-remove="videoRemove"
          >
            <el-button type="primary">上传视频</el-button>
            <template #tip>
              <div class="el-upload__tip">
                <!-- 描述 -->
              </div>
            </template>
          </el-upload>
          <div style="width: 100%" v-if="videoSrc" class="video-box">
            <IEpCircleClose @click="videoRemove" class="video-close" />
            <video controls width="500" height="300" :src="videoSrc"></video>
          </div>
        </el-form-item>
        <el-form-item label="商品描述" style="width: 100%">
          <el-input
            placeholder="商品描述"
            type="textarea"
            :rows="4"
            style="width: 100%"
            v-model="ruleForm.remark"
          />
        </el-form-item>
        <el-form-item label="商品详情" style="width: 100%">
          <richPage ref="richPageRef" />
        </el-form-item>
        <el-form-item label="商品规格参数" style="width: 100%">
          <richPage ref="specificationsRef" />
        </el-form-item>
        <el-form-item label="商品规格及SKU" style="width: 100%">
          <div v-if="!ruleForm.id" style="width: 100%">
            <div style="white-space: nowrap">
              <el-select
                style="width: 25%"
                v-model="specsValue"
                placeholder="规格"
              >
                <el-option
                  v-for="item in specsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
              <span
                style="
                  font-size: 12px;
                  color: rgb(146, 148, 150);
                  margin-left: 10px;
                "
                >*规格选择(删除)完毕后再进行数据填写！否则数据将重置！</span
              >
            </div>
            <div class="group-box">
              <el-tag
                class="el-tag-group"
                @click="selectGroup(item)"
                :class="item.check ? 'select-tag-group' : ''"
                v-for="item in specsChildren"
              >
                {{ item.name }}
              </el-tag>
            </div>
          </div>

          <div v-if="skuTable.length > 0" style="width: 100%">
            <div style="width: 100%">
              <div class="select-tag-box" v-for="item in specsData">
                <div>
                  {{ item.name }}
                </div>
                <div>
                  <el-tag
                    class="select-tag-group"
                    v-for="e in item.children"
                    @click="selectGroup(e)"
                  >
                    {{ e.name }}
                  </el-tag>
                </div>
                <IEpCircleClose class="tag-close" @click="closeTag(item)" />
              </div>
            </div>
            <el-table border class="sku-table" stripe :data="skuTable">
              <el-table-column prop="name" label="规格" />
              <el-table-column prop="sku" label="sku编号" />
              <el-table-column label="市场价格">
                <template #default="{ row }">
                  <el-input v-model="row.market" placeholder="输入市场价格" />
                </template>
              </el-table-column>
              <el-table-column label="销售价格">
                <template #default="{ row }">
                  <el-input v-model="row.selling" placeholder="输入销售价格" />
                </template>
              </el-table-column>
              <el-table-column label="虚拟销量">
                <template #default="{ row }">
                  <el-input v-model="row.virtual" placeholder="输入虚拟销量" />
                </template>
              </el-table-column>
              <el-table-column label="重量(kg)">
                <template #default="{ row }">
                  <el-input v-model="row.weight" placeholder="输入重量" />
                </template>
              </el-table-column>
              <el-table-column label="体积(m³)">
                <template #default="{ row }">
                  <el-input v-model="row.volume" placeholder="输入体积" />
                </template>
              </el-table-column>
              <el-table-column label="状态" align="center">
                <template #default="{ row }">
                  <el-checkbox
                    v-model="row.status"
                    :true-label="1"
                    :false-label="0"
                    size="large"
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item label="物流配送" prop="truck_type">
          <el-radio-group @change="truckTypeFun" v-model="ruleForm.truck_type">
            <el-radio :label="1">需要配送</el-radio>
            <el-radio :label="0">无需配送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="运费模板"
          prop="truck_code"
          v-if="ruleForm.truck_type == 1"
        >
          <el-select
            style="width: 50%"
            v-model="ruleForm.truck_code"
            placeholder="请选择"
          >
            <el-option
              v-for="item in truckOption"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group @change="truckTypeFun" v-model="ruleForm.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { addApi, saveApi } from "@/plugins/api/shopping/manage";
import { listApi as labelApi } from "@/plugins/api/system/label";
import { listApi as classApi } from "@/plugins/api/shopping/class";
import { uploadImgApi, fileApi } from "@/plugins/api/upload";
import { listApi as specsApi } from "@/plugins/api/shopping/specs";
import { listApi as freightApi } from "@/plugins/api/shopping/freight";
// 字典查询
import { listApi as dictApi } from "@/plugins/api/system/dict";
import { v4 as uuidv4 } from "uuid";
// 获取字典项（商品类型）
let typeOptions = ref([]);
function getDictionary(dict_id) {
  return new Promise((resolve, reject) => {
    dictApi({ dict_id: dict_id }).then((data) => {
      resolve(data);
    });
  });
}

let ruleForm = ref({});
let rules = {
  goods_name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  status: [{ required: true, message: "选择状态", trigger: "blur" }],
  cateid: [{ required: true, message: "选择商品分类", trigger: "blur" }],
  truck_type: [
    { required: true, message: "选择物流配送方式", trigger: "change" },
  ],
  truck_code: [{ required: true, message: "选择运费模板", trigger: "change" }],
};
let dialogVisible = ref(false);
function handleClose(done) {
  // dialogVisible.value = false;
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
}
let title = ref("");
let ruleFormRef = ref(null);
function initFun(type, row) {
  if (ruleFormRef.value) {
    ruleFormRef.value.resetFields();
  }
  if (type == "add") {
    title.value = "新增";
    ruleForm.value = {};
    coverImgList.value = [];
    sliderImgList.value = [];
    picsImgList.value = [];
    videoSrc.value = "";
    ruleForm.value.truck_type = 1;
    ruleForm.value.status = 1;
    ruleForm.value.is_integral = 0;

    specsValue.value = "";
    skuTable.value = [];

    nextTick(() => {
      richPageRef.value.valueHtml = "";
      specificationsRef.value.valueHtml = "";
    });
  } else {
    title.value = "编辑";

    ruleForm.value = Object.assign({}, row);

    // 商品封面
    coverImgList.value = [];
    if (row.cover) {
      coverImgList.value.push({
        url: imgSrc(row.cover),
      });
    }

    //轮播
    sliderImgList.value = [];
    if (row.slider) {
      row.slider.forEach((e) => {
        sliderImgList.value.push({
          url: imgSrc(e),
        });
      });
    }
    // 广告
    picsImgList.value = [];
    if (row.pics) {
      picsImgList.value.push({
        url: imgSrc(row.pics),
      });
    }
    //视频s
    videoSrc.value = "";
    if (row.video) {
      videoSrc.value = imgSrc(row.video);
    }
    //
    if (row.content) {
      nextTick(() => {
        richPageRef.value.valueHtml = row.content;
      });
    } else {
      nextTick(() => {
        richPageRef.value.valueHtml = "";
      });
    }

    if (row.info) {
      nextTick(() => {
        specificationsRef.value.valueHtml = row.info;
      });
    } else {
      nextTick(() => {
        specificationsRef.value.valueHtml = "";
      });
    }
    // sku
    skuTable.value = JSON.parse(row.data_items);
  }
  dialogVisible.value = true;
  getLabel();
  getClass();
  getTruck();
  getSpecs().then(() => {
    // 初始化默认选择 默认规格
    if (!ruleForm.value.id) {
      specsValue.value = 1;
      selectGroup(specsChildren.value[0]);
    }
  });
  getDictionary(19).then((data) => {
    typeOptions.value = data;
  });
}

const emit = defineEmits(["refreshList"]);
function submit() {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      let obj = Object.assign({}, ruleForm.value);
      obj.content = richPageRef.value.valueHtml;
      obj.info = specificationsRef.value.valueHtml;
      if (skuTable.value.length == 0) {
        return ElMessage.warning("请填写sku信息！");
      }
      obj.data_items = skuTable.value;

      if (!ruleForm.value.id) {
        obj.data_specs = specsData.value.map((item) => {
          item.list = item.children.map((e) => e);
          return item;
        });
        addApi(obj).then((data) => {
          ElMessage.success("新增成功！");
          dialogVisible.value = false;
          emit("refreshList");
        });
      } else {
        obj.data_specs = JSON.parse(obj.data_specs);
        saveApi(obj).then((data) => {
          ElMessage.success("修改成功！");
          dialogVisible.value = false;
          emit("refreshList");
        });
      }
    }
  });
}
// 商品标签
let labelOptions = ref([]);
function getLabel() {
  let obj = Object.assign(
    {},
    {
      type: "商品",
    }
  );
  labelApi(obj).then((data) => {
    labelOptions.value = data.list;
  });
}
// 分类编号
let classOptions = ref([]);
function getClass() {
  classApi({}).then((data) => {
    classOptions.value = data;
  });
}
// 商品封面
let coverLoading = ref(false);
let coverImgList = ref([]);
function coverOnChange(file) {
  let formData = new FormData();
  formData.append("file", file.raw);
  coverLoading.value = true;
  uploadImgApi(formData)
    .then((data) => {
      let obj = {
        url: import.meta.env.VITE_APP_BASE_API + data.file_url,
      };
      if (coverImgList.value.length > 0) {
        coverImgList.value = [];
        coverImgList.value.push(obj);
      } else {
        coverImgList.value.push(obj);
      }
      ruleForm.value.cover = data.file_url;
      coverLoading.value = false;
    })
    .catch(() => {
      coverLoading.value = false;
    });
}
function coverRemove(index) {
  coverImgList.value.splice(index, 1);
  ruleForm.value.cover = "";
}
// 轮播图片
let sliderLoading = ref(false);
let sliderImgList = ref([]);
function sliderOnChange(file) {
  let formData = new FormData();
  formData.append("file", file.raw);
  sliderLoading.value = true;
  uploadImgApi(formData)
    .then((data) => {
      let obj = {
        url: import.meta.env.VITE_APP_BASE_API + data.file_url,
      };

      sliderImgList.value.push(obj);
      if (!ruleForm.value.slider) {
        ruleForm.value.slider = [];
      }
      ruleForm.value.slider.push(data.file_url);
      sliderLoading.value = false;
    })
    .catch(() => {
      sliderLoading.value = false;
    });
}
function sliderRemove(index) {
  sliderImgList.value.splice(index, 1);
  ruleForm.value.slider.splice(index, 1);
}
// 广告图片
let picsLoading = ref(false);
let picsImgList = ref([]);
function picsOnChange(file) {
  let formData = new FormData();
  formData.append("file", file.raw);
  picsLoading.value = true;
  uploadImgApi(formData)
    .then((data) => {
      let obj = {
        url: import.meta.env.VITE_APP_BASE_API + data.file_url,
      };
      if (picsImgList.value.length > 0) {
        picsImgList.value = [];
        picsImgList.value.push(obj);
      } else {
        picsImgList.value.push(obj);
      }
      ruleForm.value.pics = data.file_url;
      picsLoading.value = false;
    })
    .catch(() => {
      picsLoading.value = false;
    });
}
function picsRemove(index) {
  picsImgList.value.splice(index, 1);
  ruleForm.value.pics = "";
}
// 视频
let videoSrc = ref("");
function videoOnChange(file) {
  let formData = new FormData();
  formData.append("file", file.raw);
  fileApi(formData).then((resp) => {
    if (resp.file_url) {
      videoSrc.value = imgSrc(resp.file_url);
      ruleForm.value.video = resp.file_url;
    } else {
      ElMessage.danger("视频上传失败！请重新上传！");
    }
  });
}
function videoRemove() {
  videoSrc.value = "";
  ruleForm.value.video = "";
}
// 富文本
let richPageRef = ref(null);
let specificationsRef = ref(null);
// 规格
let specsValue = ref("");
let specsChildren = computed(() => {
  let arr = [];
  specsList.value.forEach((item) => {
    if (item.id == specsValue.value) {
      arr = item.children;
    }
  });

  return arr;
});
let specsData = computed(() => {
  let arr = [];
  specsList.value.forEach((item) => {
    if (
      item.children.some((ele) => {
        return ele.check;
      })
    ) {
      let obj = Object.assign({}, item);
      obj.children = [];
      delete obj.spec;
      item.children.forEach((e) => {
        if (e.check) {
          obj.children.push(e);
        }
      });
      arr.push(obj);
    }
  });
  return arr;
});
let specsList = ref([]);

function getSpecs() {
  return new Promise((resolve, reject) => {
    let obj = Object.assign(
      {},
      {
        page: 1,
        pageSize: 1000,
      }
    );
    specsApi(obj).then((data) => {
      specsList.value = data.list.map((item, i) => {
        if (item.spec) {
          let children = item.spec.split(",");
          item.children = children.map((ele, j) => {
            return {
              pid: item.id,
              id: `${item.id}-${ele}`,
              name: ele,
              group: item.name,
            };
          });
        }
        return item;
      });
      resolve();
    });
  });
}
function closeTag(row) {
  row.children.forEach((item) => {
    item.check = false;
  });
  skuTable.value = setSku();
}
function selectGroup(item) {
  item.check = !item.check;

  skuTable.value = setSku();
}
// 生成sku
function setSku() {
  let skuList = generateSKUs(specsData.value);

  let arr = [];
  if (skuList && skuList.length > 0) {
    skuList.forEach((item) => {
      let obj = {};
      let a = [];
      let nameArr = [];
      item.forEach((ele) => {
        let str = `${ele["attributeName"]}::${ele["optionGroup"]}`;
        let name_str = `${ele["optionGroup"]}`;
        a.push(str);
        nameArr.push(name_str);
      });
      obj.name = nameArr.join("-");
      obj.key = a.join(";;");
      obj.sku = "sku-" + uuidv4();
      obj.check = true;
      obj.status = 1;
      arr.push(obj);
    });
  } else {
    arr = [];
  }
  return arr;
}

let skuTable = ref([]);

function generateSKUs(attributes) {
  const result = [];
  function generateCombinations(index, currentCombination) {
    if (index === attributes.length) {
      result.push(currentCombination);
      return;
    }
    for (const option of attributes[index].children) {
      if (option.check) {
        const newCombination = [...currentCombination];
        newCombination.push({
          attributeId: attributes[index].id,
          attributeName: attributes[index].name,
          optionGroup: option.name,
        });
        generateCombinations(index + 1, newCombination);
      }
    }
  }

  generateCombinations(0, []);
  if (attributes.length == 0) {
    return [];
  } else {
    return result;
  }
}
// 物流配送
function truckTypeFun(data) {
  ruleForm.value.truck_code = "";
}
let truckOption = ref([]);
function getTruck() {
  freightApi({}).then((data) => {
    truckOption.value = data;
  });
}
//
function imgSrc(path) {
  return import.meta.env.VITE_APP_BASE_API + path;
}

//
defineExpose({
  initFun,
});
onMounted(() => {});
</script>
<style scoped lang="scss">
.manage-dialog {
  .img-box {
    display: inline-block;
    margin-right: 5px;
    // margin-bottom: 10px;
    width: 148px;
    position: relative;

    img {
      width: 100%;
      height: 140px;
      object-fit: cover;
    }

    .occlusion {
      display: none;
      width: 100%;
      height: 140px;
      background: #9e9c9c75;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 99;
      text-align: center;

      .del {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        line-height: 148px;
        color: #464444;
        cursor: pointer;
        font-size: large;

        &:hover {
          color: rgb(130, 131, 133);
        }
      }
    }

    &:hover {
      .occlusion {
        display: block;
      }
    }
  }

  .video-box {
    position: relative;

    .video-close {
      position: absolute;
      top: 0;
      left: 500px;
      font-size: 20px;
      cursor: pointer;

      &:hover {
        color: skyblue;
      }
    }
  }

  // 规格
  .el-tag-group {
    margin: 0 10px 5px 0;
    cursor: pointer;
    user-select: none;
  }

  .select-tag-group {
    background: #409eff;
    color: white;
    margin: 0 10px 5px 0;
    user-select: none;
    cursor: pointer;
  }

  .group-box {
    width: 100%;
    margin-top: 10px;
  }

  .select-tag-box {
    border: 1px solid #d5d3d3;
    padding: 10px;
    box-sizing: border-box;
    margin-bottom: 10px;
    position: relative;

    .tag-close {
      position: absolute;
      top: 10px;
      right: 10px;
      cursor: pointer;

      &:hover {
        color: #409eff;
      }
    }
  }

  .sku-table {
    :deep(.el-input__wrapper) {
      padding: 0 5px;
    }
  }

  :deep(.el-form-item) {
    width: 50%;
    margin-right: 0;
    padding-right: 10px;
    box-sizing: border-box;

    .el-input {
      width: 100%;
    }
  }

  :deep(.el-input__wrapper) {
    width: 100% !important;
  }
}
</style>
